package com.huilai.platform.country_platform.service;

import com.huilai.platform.country_platform.core.Result;
import com.huilai.platform.country_platform.core.ResultGenerator;
import com.huilai.platform.country_platform.dto.ChatListDTO;
import com.huilai.platform.country_platform.dto.ChatMessageDTO;
import com.huilai.platform.country_platform.model.ChatLink;
import com.huilai.platform.country_platform.model.ChatList;
import com.huilai.platform.country_platform.model.ChatMessage;
import com.huilai.platform.country_platform.model.InformationRecruitment;
import com.huilai.platform.country_platform.repository.ChatLinkReposity;
import com.huilai.platform.country_platform.repository.ChatListReposity;
import com.huilai.platform.country_platform.repository.ChatMessageReposity;
import com.huilai.platform.country_platform.repository.UserRepository;
import com.huilai.platform.country_platform.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 作者：洪霓
 * 日期：2023/3/27
 * 注释：
 */
@Service
public class ChatService {

    @Autowired
    private ChatLinkReposity chatLinkReposity;

    @Autowired
    private ChatListReposity chatListReposity;

    @Autowired
    private ChatMessageReposity chatMessageReposity;

    @Autowired
    private UserRepository userRepository;

    public boolean isFirstChat(Integer fromId, Integer toId){
        ChatLink chatLink1 = chatLinkReposity.findChatLinkByFromIdAndToId(fromId, toId);
        ChatLink chatLink2 = chatLinkReposity.findChatLinkByFromIdAndToId(toId, fromId);
        if (chatLink1 == null && chatLink2 == null && fromId!=null && toId!=null && fromId != toId){
            ChatLink chatLink = new ChatLink(fromId, toId);
            chatLinkReposity.addChatLink(chatLink);
            ChatLink chatLink3 = chatLinkReposity.findChatLinkByFromIdAndToId(fromId, toId);

            ChatList fromUserList = new ChatList(chatLink3.getId(), fromId, toId,  0, 0, 0);
            ChatList toUserList = new ChatList(chatLink3.getId(), toId, fromId, 0, 0, 0);

            chatListReposity.addChatList(fromUserList);
            chatListReposity.addChatList(toUserList);

//            插入一条空白数据
            ChatMessage chatMessage = new ChatMessage(chatLink3.getId(), fromId, toId, "",  1);
            chatMessageReposity.addChatMessage(chatMessage);
            return true;
        }
        return false;
    }

    public ChatLink findChatLinkByFromIdAndToId(Integer fromId, Integer toId){
        return chatLinkReposity.findChatLinkByFromIdAndToId(fromId, toId);
    }

    public  ChatLink findChatLink(Integer fromId, Integer toId){
        ChatLink chatLink = chatLinkReposity.findChatLinkByFromIdAndToId(fromId, toId);
        if (chatLink == null){
            chatLink = chatLinkReposity.findChatLinkByFromIdAndToId(toId, fromId);
        }
        return chatLink;
    }

    public void addMessage(ChatMessage chatMessage){
        chatMessageReposity.updateIsLastest(chatMessage.getLinkId());
        ChatList chatList = chatListReposity.findChatListByLinkIdAndFromIdAndToId(chatMessage.getLinkId(), chatMessage.getFromId(), chatMessage.getToId());
        Integer flag = chatList.getFromWindow() + chatList.getToWindow();
        // 1--只有一方在窗口中 未读数加给接收方，2--两者都在窗口中 清除未读数
        if (flag == 1) {
            //更新未读数,
            chatListReposity.updateUnread(chatMessage.getFromId(), chatMessage.getToId(), 1, chatMessage.getLinkId());
        } else if (flag == 2) {
            //清空所有的未读数
            chatListReposity.clearUnread(chatMessage.getFromId(), chatMessage.getToId(), chatMessage.getLinkId());
            chatListReposity.clearUnread(chatMessage.getToId(), chatMessage.getFromId(), chatMessage.getLinkId());
        }

        //保存聊天记录
        chatMessageReposity.addChatMessage(chatMessage);

    }

    public List<ChatListDTO> getFromUserChatList(Integer fromId){
//        PageRequest pageable = PageRequest.of(0, 10);
        List<ChatList> chatLists = chatListReposity.findAll((root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(cb.equal(root.get("fromId"),fromId));
            query.where(predicates.toArray(new Predicate[]{}));
            query.orderBy(cb.desc(root.get("linkId")));
            return null;
        });
        List<ChatListDTO> chatListDTOList = new ArrayList<>();
        for(ChatList chatList:chatLists){
            Integer linkId = chatList.getLinkId();
            Integer fromId2 = chatList.getFromId();
            Integer toId = chatList.getToId();
            ChatMessage chatMessage = chatMessageReposity.findChatMessageByLinkIdAndFromIdAndIsLastest(linkId, fromId2, 1);
            if (chatMessage == null){
                chatMessage = chatMessageReposity.findChatMessageByLinkIdAndFromIdAndIsLastest(linkId, toId, 1);
            }
            ChatListDTO chatListDTO = new ChatListDTO(
                    linkId,
                    userRepository.findUserById(toId).getUsername(),
                    chatMessage.getContent(),
                    chatList.getUnread(),
                    DateUtil.fromDateToString(chatMessage.getSendTime()),
                    chatList.getFromWindow()
            );
            chatListDTOList.add(chatListDTO);
        }
        return chatListDTOList;
    }

    public List<ChatMessageDTO> getRecentChatRecords(Integer linkId, Integer fromId, Integer toId, Integer pageNum, Integer pageSize){
        PageRequest pageable = PageRequest.of(pageNum, pageSize);
//        Page<ChatMessage> chatMessageDTOList = chatMessageReposity.findAll((root, query, cb) -> {
//            List<Predicate> predicates = new ArrayList<>();
//            predicates.add(cb.equal(root.get("linkId"),linkId));
//            query.where(predicates.toArray(new Predicate[]{}));
//            query.orderBy(cb.asc(root.get("sendTime")));
//            return null;
//        },pageable);
//        Page<ChatMessageDTO> chatMessageDTOPage = chatMessageDTOList.map(chatMessage -> {
//            ChatMessageDTO chatMessageDTO = new ChatMessageDTO(
//                    userRepository.findUserById(chatMessage.getFromId()).getUsername(),
//                    chatMessage.getContent(),
//                    chatMessage.getSendTime()
//            );
//            return chatMessageDTO;
//        });

        List<ChatMessage> chatMessageList = chatMessageReposity.findAll((root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(cb.equal(root.get("linkId"),linkId));
            query.where(predicates.toArray(new Predicate[]{}));
            query.orderBy(cb.asc(root.get("sendTime")));
            return null;
        });
        List<ChatMessageDTO> chatMessageDTOList = new ArrayList<>();
        for (ChatMessage chatMessage:chatMessageList){
            ChatMessageDTO chatMessageDTO = new ChatMessageDTO(
                    userRepository.findUserById(chatMessage.getFromId()).getUsername(),
                    chatMessage.getContent(),
                    DateUtil.fromDateToString(chatMessage.getSendTime())
            );
            chatMessageDTOList.add(chatMessageDTO);
        }

        System.out.println(linkId);
        System.out.println(fromId);
        System.out.println(toId);

        chatListReposity.clearUnread(fromId, toId, linkId);
        return chatMessageDTOList;
//        return ResultGenerator.genSuccessResult(chatMessageList);

    }

    public Integer updateWindow(Integer linkId, Integer id, Integer window){
        Integer integer1 = chatListReposity.updateFromWindow(linkId, id, window);
        Integer integer2 = chatListReposity.updateToWindow(linkId, id, window);
        if (integer1 == 1&& integer2 == 1){
            return 1;
        }
        return -1;
    }

    public void resetWindows(String username){

    }
}
